<?php

namespace app\admin\controller\order;

use app\admin\model\User;
use app\common\common\Common;
use app\common\controller\Backend;
use app\common\helpers\ImageUtil;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

/**
 * 订单列管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\shop\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Order;
        $this->view->assign("statusList", $this->model->getUserStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['user','shop'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_number','status','uid','shop_id','goods_name','price','pack_price','distribution_price','num','actual_price','order_time','payment_time','end_time','harvest_user','harvest_phone','refund_status']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
				$row->visible(['shop']);
				$row->getRelation('shop')->visible(['shop_name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign("shop_id", 0);
        return $this->view->fetch();
    }

    /**
     * @throws \think\exception\DbException
     * 取消订单
     */
    public function up_status($ids){
        $row = $this->model->get($ids);
        if($row['refund_status'] == '1'){
            $this->error('退款中');
        }
        if($row['refund_status'] == '2'){
            $this->error('已退款,注意查收');
        }
        $refund_number = \app\common\controller\Common::orderRefundNumber();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $row->before_refund_status= $row->status;
            $row->refund_number=$refund_number;
            $row->apply_time=date('Y-m-d H:i:s');
            $row->refund_time = date('Y-m-d H:i:s');
            $row->end_time =date('Y-m-d H:i:s');
            $row->refund_status =2;
            $row->status=13; //平台取消
            $res =  \app\common\controller\Common::orderRefund($row,$refund_number);
            $result = $row->allowField(true)->save();
            if($res['result_code'] != 'SUCCESS'){
                Db::rollback();
                $this->error(\app\common\controller\Common::wechatCode($res['err_code']));
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('退款申请成功');

    }
    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $info = $row->toArray();
        $user = User::get($info['uid']);
        $shop = \app\admin\model\Shop::get($info['shop_id']);
        $StatusList = $this->model->getUserStatusList();
        $RefundStatusList = $this->model->getRefundStatusList();
        $info2 = [
            'Shop.shop_name'=>$shop['shop_name'],
            'Order_user'=>$user['nickname'],
            'order_number'=>$info['order_number'],
            'status'=>isset($StatusList[$info['status']]) ? $StatusList[$info['status']] :"",
            'goods_img'=>$info['goods_img'],
            'goods_name'=>$info['goods_name'],
            'guige'=>$info['guige'],
            'price'=>$info['price'],
            'pack_price'=>$info['pack_price'],
            'distribution_price'=>$info['distribution_price'],
            'num'=>$info['num'],
            'actual_price'=>$info['actual_price'],
            'order_time'=>$info['order_time'],
            'payment_time'=>$info['payment_time'],
            'harvest_time'=>$info['harvest_time'],
            'end_time'=>$info['end_time'],
            'harvest_address'=>$info['harvest_address'],
            'harvest_user'=>$info['harvest_user'],
            'harvest_phone'=>$info['harvest_phone'],
            'refund_number'=>$info['refund_number'],
            'apply_time'=>$info['apply_time'],
            'before_refund_status'=>isset($StatusList[$info['before_refund_status']]) ? $StatusList[$info['before_refund_status']] :"",
            'refund_status'=>isset($RefundStatusList[$info['before_refund_status']]) ? $RefundStatusList[$info['before_refund_status']] :"",
        ];
        $this->view->assign("row", $info2);
        return $this->view->fetch();
    }

//`refund_status` int(1) DEFAULT '0' COMMENT '退款状态：1退款中 2退款成功 3 退款失败',

}
